<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索框 -->
    <el-input placeholder="请输入内容" v-model="inputValue" class="input-with-select">
      <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
    </el-input>
    <el-button type="primary" plain @click="showaddUser">添加用户</el-button>
    <!-- 表格 -->
    <template>
      <el-table style="width: 100%" border :data="usersList">
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>

        <el-table-column label="用户状态" prop>
          <template v-slot="obj">
            <el-switch
              v-model="obj.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeState(obj.row.id,obj.row.mg_state)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button
              type="primary"
              plain
              size="small"
              class="el-icon-edit"
              @click="editUser(row)"
            ></el-button>
            <el-button
              type="danger"
              plain
              size="small"
              class="el-icon-delete"
              @click="delUser(row.id)"
            ></el-button>
            <el-button
              type="success"
              plain
              class="el-icon-check"
              size="small"
              @click="showAssginVisible(row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 分页 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%" @close="closeDialog">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改" :visible.sync="editVisible" width="40%">
      <el-form :data="editForm" label-width="80px">
        <el-form-item label="用户名:" ref="editForm" :rules="rules" :model="editForm">
          <el-tag>{{editForm.username}}</el-tag>
        </el-form-item>
        <el-form-item label="邮箱:">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机:">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editOK">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色框 -->
    <el-dialog title="修改" :visible.sync="assginVisible" width="40%">
      <el-form :data="assginForm" label-width="80px">
        <el-form-item label="角色名:" :model="assginForm">
          <el-tag>{{assginForm.username}}</el-tag>
        </el-form-item>
        <el-form-item label="角色列表:">
          <el-select v-model="assginForm.rid" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assginVisible = false">取 消</el-button>
          <el-button type="primary" @click="assginOk">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getUserList()
  },

  data () {
    return {
      inputValue: '',
      query: '',
      pagenum: 1, // 当前页
      pagesize: 2, // 每页显示几条
      usersList: [],
      total: 0,
      dialogVisible: false,
      editVisible: false,
      assginVisible: false,
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'change']
          },
          { min: 3, max: 5, message: '长度3-12', trigger: ['blur', 'change'] }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['blur', 'change']
          },
          { min: 3, max: 5, message: '长度3-12', trigger: ['blur', 'change'] }
        ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: ['blur', 'change']
          }
        ]
      },
      editForm: {
        username: '',
        mobile: '',
        email: '',
        id: ''
      },
      assginForm: {
        username: '',
        id: '',
        rid: ''
      },
      options: []
    }
  },
  methods: {
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.getUserList()
      this.pagenum = 1
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.getUserList()
    },
    getUserList () {
      this.$axios
        .get('users', {
          params: {
            query: this.query,
            pagenum: this.pagenum,
            pagesize: this.pagesize
          }
        })
        .then(res => {
          const { data, meta } = res
          this.total = data.total
          if (meta.status === 200) {
            this.usersList = data.users
          }
        })
    },
    searchUser () {
      console.log(123)
      this.query = this.inputValue
      this.pagenum = 1

      this.getUserList()
    },
    changeState (id, type) {
      this.$axios.put(`users/${id}/state/${type}`).then(res => {
        if (res.status === 200) {
          this.$message.success(res.data.meta.msg)
        } else {
          this.$message.error(res.data.meta.msg)
        }
      })
    },
    // 删除
    async delUser (id) {
      try {
        await this.$confirm('你确定要删除这个东东吗', '友情提醒', {
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`users/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          if (this.usersList.length === 1 && this.pagenum > 1) {
            this.pagenum--
          }
          this.getUserList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 显示添加框
    showaddUser () {
      this.dialogVisible = true
    },
    // 添加用户
    async addUser () {
      try {
        const { meta } = await this.$axios.post('users', this.form)
        // console.log(res)
        if (meta.status === 201) {
          this.$message.success(meta.msg)
          this.dialogVisible = false
          this.pagenum = Math.ceil(++this.total / this.pagesize)
          this.getUserList()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 关闭对话框，重置内容
    closeDialog () {
      this.$refs.form.resetFields()
    },
    // 显示修改框，并数据回显
    editUser (row) {
      console.log(row)
      this.editVisible = true
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
    },
    // 修改框确认的时候，发送ajax请求
    async editOK () {
      const id = this.editForm.id
      const { meta } = await this.$axios.put(`users/${id}`, {
        email: this.editForm.email,
        mobile: this.editForm.mobile
      })
      // console.log(res)
      if (meta.status === 200) {
        this.editVisible = false
        this.getUserList()
      }
    },
    // 显示分配角色框
    async showAssginVisible (row) {
      this.assginVisible = true
      this.assginForm.username = row.username
      this.assginForm.id = row.id

      const res = await this.$axios.get(`users/${row.id}`)
      const rid = res.data.rid
      this.assginForm.rid = rid === -1 ? '请选择' : rid
      // const
      const { data, meta } = await this.$axios.get('roles')
      // console.log(result)
      if (meta.status === 200) {
        this.options = data
      }
    },
    // 分配角色发送ajax渲染页面
    async assginOk () {
      const { id, rid } = this.assginForm
      const { meta } = await this.$axios.put(`users/${id}/role`, {
        rid
      })
      // console.log(res)
      if (meta.status === 200) {
        this.$message.success(meta.msg)
        this.assginVisible = false
        this.getUserList()
      } else {
        this.$message.error(meta.msg)
      }
    }
  }
}
</script>

<style lang="less">
.users {
  .el-breadcrumb {
    height: 40px;
    line-height: 40px;
    margin-bottom: 10px;
    border-bottom: 1px solid #999;
  }
  .input-with-select {
    width: 366px;
    margin-right: 120px;
    margin-bottom: 10px;
  }
}
</style>
